package com.vancouver.knows.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.BusinessImageInfo;
import com.vancouver.knows.business.bean.CityDiscountDetailInfo;
import com.vancouver.knows.ui.activity.citydiscount.BusinessImageViewerActivity;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.activity.userpost.CreateUserPostActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.util.AppUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-08-18.
 */
public class ImageGalleryActivity extends BaseActivity implements IResultReceiver {

    public static final String POST_ID_EXTRA = "post_id_extra";

    @Bind(R.id.image_gallery_recycler_view)
    RecyclerView mImageGalleryRecyclerView;
    @Bind(R.id.toolbar_title)
    TextView mToolbarTitle;

    private BusinessModule bModule;
    private BSharedPrefManager bSharedPrefManager;
    private String mPostId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_gallery);

        mImageGalleryRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));

        mPostId = getIntent().getStringExtra(POST_ID_EXTRA);
        if (StringUtil.isEmptyString(mPostId)) {
            return;
        }

        bModule = imContext.getBusinessModule();

        CityDiscountDetailInfo cityDiscountDetailInfo = imContext.getBusinessModule().getCacheManager().getDiscountDetailInfoMap().get(mPostId);
        if (cityDiscountDetailInfo != null && cityDiscountDetailInfo.getBusinessUserImages() != null) {
            bSharedPrefManager = imContext.getSharedPrefManager();
            mImageGalleryRecyclerView.setAdapter(new ImageGalleryAdapter(bSharedPrefManager, mPostId, cityDiscountDetailInfo.getBusinessUserImages()));
            mToolbarTitle.setText(getString(R.string.photo_gallery_title, cityDiscountDetailInfo.getBusinessUserImages().size()));
        } else {
            finish();
        }
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CreateUserPostActivity.ADD_PHOTOS_REQUEST && resultCode == RESULT_OK) {
            ATaskMark aTaskMark = bModule.getTaskMarkPool().getFetchDiscountDetailTaskMark(mPostId);
            aTaskMark.setTaskType(ATaskMark.TYPE_REFRESH);
            bModule.getServiceWrapper().fetchDiscountDetail(this, aTaskMark, mPostId, bSharedPrefManager.getUserId(), imContext.latitude, imContext.longitude);
        }
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception != null) {
            Log.e(TAG, exception.getExMessage());
        }
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);

        switch (msg.what) {
            case Constants.BUSINESS_STATUS_CITYDISCOUNT_IMAGES_CHANGE:
                CityDiscountDetailInfo cityDiscountDetailInfo = imContext.getBusinessModule().getCacheManager().getDiscountDetailInfoMap().get(mPostId);
                if (cityDiscountDetailInfo != null && cityDiscountDetailInfo.getBusinessUserImages() != null) {
                    bSharedPrefManager = imContext.getSharedPrefManager();
                    mImageGalleryRecyclerView.setAdapter(new ImageGalleryAdapter(bSharedPrefManager, mPostId, cityDiscountDetailInfo.getBusinessUserImages()));
                    mToolbarTitle.setText(getString(R.string.photo_gallery_title, cityDiscountDetailInfo.getBusinessUserImages().size()));
                }
                break;
        }
    }

    public static class ImageGalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private BSharedPrefManager bSharedPrefManager;
        private String mPostId;
        private List<BusinessImageInfo> mBusinessUserImages;

        public ImageGalleryAdapter(BSharedPrefManager bSharedPrefManager, String postId, List<BusinessImageInfo> businessUserImages) {
            this.bSharedPrefManager = bSharedPrefManager;
            this.mPostId = postId;
            this.mBusinessUserImages = businessUserImages;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            int size = AppUtils.getWindowWidth(parent.getContext()) / 4;
            ImageView imageView = new ImageView(parent.getContext());
            imageView.setLayoutParams(new RecyclerView.LayoutParams(size, size));
            imageView.setBackgroundColor(Color.WHITE);
            return new ImageViewHolder(imageView);
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int  position) {
            if (position != getItemCount() - 1) {
                BusinessImageInfo businessImageInfo = mBusinessUserImages.get(position);
                holder.itemView.setPadding(0, 0, 0, 0);
                Picasso.with(holder.itemView.getContext()).load(businessImageInfo.getImageUrl()).fit().centerCrop().into((ImageView) holder.itemView);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(holder.itemView.getContext(), BusinessImageViewerActivity.class);
                        intent.putExtra(BusinessImageViewerActivity.POST_ID_EXTRA, mPostId);
                        intent.putExtra(BusinessImageViewerActivity.INDEX_EXTRA, holder.getAdapterPosition());
                        holder.itemView.getContext().startActivity(intent);
                    }
                });
            } else {
                ImageView imageView = (ImageView) holder.itemView;
                imageView.setImageResource(R.drawable.action_add_image);
                int padding = AppUtils.dip2px(holder.itemView.getContext(), 30);
                imageView.setPadding(padding, padding, padding, padding);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (bSharedPrefManager.getUserId() == null) {
                            holder.itemView.getContext().startActivity(new Intent(holder.itemView.getContext(), LoginActivity.class));
                            return;
                        }

                        Intent intent = new Intent(holder.itemView.getContext(), CreateUserPostActivity.class);
                        intent.putExtra(CreateUserPostActivity.ADD_PHOTOS_MODE_EXTRA, true);
                        intent.putExtra(CreateUserPostActivity.POST_ID_EXTRA, mPostId);
                        ((AppCompatActivity) holder.itemView.getContext()).startActivityForResult(intent, CreateUserPostActivity.ADD_PHOTOS_REQUEST);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return mBusinessUserImages.size() + 1;
        }

        public static class ImageViewHolder extends RecyclerView.ViewHolder {

            public ImageViewHolder(View itemView) {
                super(itemView);
            }
        }

    }

}
